package com.gxy.learn.verify.web;

import com.alibaba.fastjson.JSONObject;
import com.gxy.learn.verify.web.req.ParamVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description(参数验证  参考Spring https://www.baeldung.com/spring-validate-requestparam-pathvariable)
 * author: Gao xueyong
 * Create at: 2020/4/12 12:20 下午
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/requestParam")
public class RequestParamController {
    @RequestMapping(value = "/get/checkParam", method = RequestMethod.GET)
    public Map<String, Object> checkParam(
            @RequestParam(value = "name") @NotBlank(message = "name 不能为空!") String name,
            @RequestParam(value = "age") @NotNull(message = "age 不能为空!") @Max(value = 4,message = "age不能大于4") @Min(value = 2,message = "age不能小于2") Integer age,
            @RequestParam(value = "list") @NotNull(message = "list 不能为空!") List<String> list,
            @RequestParam(value = "email") @NotBlank(message = "email 不能为空!")
            @Pattern(regexp = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$", message = "email格式不正确！") String email,
            @RequestParam(value = "pastDate") @NotNull(message = "pastDate不能为null") @DateTimeFormat(pattern = "yyyy-MM-dd")
            @Past(message = "pastDate必须是一个过去的时间！") Date pastDate,
            @RequestParam(value = "fatureDate") @NotNull(message = "fatureDate不能为null") @DateTimeFormat(pattern = "yyyy-MM-dd")
            @Future(message = "fatureDate必须是一个将来的时间！") Date fatureDate) {
        //自己主动获取 并根据需求严衡
        Map<String, Object> param = new HashMap<>();
        param.put("name", name);
        param.put("age", age);
        param.put("list", list);
        param.put("email", email);
        param.put("pastDate", pastDate);
        param.put("fatureDate", fatureDate);
        return param;
    }

    @RequestMapping(value = "/get/checkParam/requestBody", method = RequestMethod.POST)
    public String checkStr(@Valid @RequestBody ParamVo vo){
        return JSONObject.toJSONString(vo);
    }
}
